var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors')
var indexRouter = require('./routes/index');
var yzkRouter = require('./routes/yzk');
var cxbRouter = require('./routes/cxb');
// var fxsRouter = require('./routes/fxs');
var fxsRouter = require("./routes/fxs/index");
var fxsRouter2 = require('./routes/fxs/comment');
                      
var szhRouter = require('./routes/szh');
var shopsRouter = require('./routes/shops')
var goodsRouter = require('./routes/goods')
const { createServer } = require("http");
//导入 socket.io 模块，并将其赋予变量
//socket.io 是一个实现实时双向通信的库。通过这个库，可以轻松地在服务器和客户端之间建立实时通信连接。
//创建服务器实例与http服务器集成
const { Server } = require("socket.io");
var { roomModel } = require("./model/model")

var shopsRouter = require('./routes/shops')
var goodsRouter = require('./routes/goods')



var app = express();
//创建一个http服务器，这个服务器使用app传来的http请求
const httpServer = createServer(app);
//socket.io服务器的实例
const io = new Server(httpServer, { cors: {
  origin: "*", // 允许特定的客户端源访问
  methods: ["GET", "POST"], // 允许的 HTTP 方法
  allowedHeaders: ["Content-Type", "Authorization"], // 允许的请求头
}, });
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors())
//服务器监听客户端的连接
io.on("connection", async(socket) => {
  //根据客户端的两个用户id把房间名返回
  let roomls = await roomModel.find()
  roomls.filter(item => item.users.indexOf(socket.handshake.query.uid) !== -1 && item.users.indexOf(socket.handshake.query.eid) !== -1)
  socket.emit('welcome', roomls[0].roomname)
  //监听客户端加入聊天房间
  socket.on('joinRoom', async(roomName, data) => {
    //根据客户端data数据来判断这两个用户的聊天室是否已创建
    //判断房间是否存在，不存在的话先创建
    // let roomls = await roomModel.find()
    // if (!(roomls.some(item => item.users.indexOf(data._id) !== -1 && item.users.indexOf(data.el_id) !== -1))) {
    //   roomModel.create({roomname: roomName, users: [data._id, data.el_id], messages: []})
    // }
    //客户端链接聊天房间
    socket.join(roomName)
    //返回最新聊天记录给客户端
    let payloves = await roomModel.find({_id: data.rid})
    io.to(roomName).emit('roomMessageReceived', payloves)
    //服务器监听来自客户端在房间发送消息
    //data:消息的发生者和房间的id(用于存储消息到数据库)
    socket.on('roomMessage', async(message, roomName, data) => {
      //存储消息记录到数据库
      await roomModel.findOneAndUpdate(
        {_id: data.roomid},
        {
          $push: {
            messages: { sender: data.sender, content: message }
          }
        }
      )
      //返回最新聊天记录给客户端
      let payloves = await roomModel.find({_id: data.roomid})
      io.to(roomName).emit('roomMessageReceived', payloves)
    });
  });
});
//socket.io的端口号
httpServer.listen(3001);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/upload', express.static(path.join(__dirname, 'upload')));

app.use('/', indexRouter);
app.use('/yzk', yzkRouter);
app.use('/cxb', cxbRouter);
app.use("/shops", shopsRouter)
app.use("/goods", goodsRouter)
app.use('/fxs', fxsRouter);
app.use('/fxs', fxsRouter2);

app.use('/szh', szhRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  // res.locals.message = err.message;
  // res.locals.error = req.app.get('env') === 'development' ? err : {};

  // // render the error page
  // res.status(err.status || 500);
  // res.render('error');
  console.log(err)
});

module.exports = app;
